import { defineStore } from 'pinia'
import { api, generateDocx } from '@/utils/api'

export const useProjectStore = defineStore('project', {
  state: () => ({
    projects: [],
    pagination: {
      currentPage: 1,
      totalPages: 1,
      totalItems: 0,
      itemsPerPage: 10
    },
    currentProject: null
  }),

  getters: {
    getProjects: (state) => state.projects,
    getCurrentProject: (state) => state.currentProject
  },

  actions: {
    // 获取项目列表
    async fetchProjects(params) {
      try {
        const response = await api.projects.list(params)
        this.projects = response.data || []
        this.pagination = response.pagination
        console.log(this.pagination,'this.pagination',response)
        return this.projects
      } catch (error) {
        console.error('获取项目列表失败:', error)
        // 如果API失败，返回默认数据作为fallback
        if (this.projects.length === 0) {
          this.projects = this.getDefaultProjectsData()
        }
        return this.projects
      }
    },

    // 获取项目前置页
    async fetchFrontMatter(projectId) {
      try {
        const res = await api.projects.getFrontMatter(projectId)
        return res.data?.frontMatter || []
      } catch (error) {
        console.error('获取项目前置页失败:', error)
        return []
      }
    },

    // 保存项目前置页
    async saveFrontMatter(projectId, frontMatter) {
      try {
        await api.projects.updateFrontMatter(projectId, { frontMatter })
        return true
      } catch (error) {
        console.error('保存项目前置页失败:', error)
        throw error
      }
    },

    // 获取项目详情
    async fetchProject(projectId) {
      try {
        const response = await api.projects.getById(projectId)
        return response.data
      } catch (error) {
        console.error('获取项目详情失败:', error)
        throw error
      }
    },

    // 获取项目完整配置
    async fetchProjectConfig(projectId) {
      try {
        const response = await api.projects.getConfig(projectId)
        return response.data
      } catch (error) {
        console.error('获取项目配置失败:', error)
        throw error
      }
    },

    // 创建新项目
    async createProject(projectData) {
      try {
        const response = await api.projects.create(projectData)
        const newProject = response.data
        this.projects.push(newProject)
        return newProject
      } catch (error) {
        console.error('创建项目失败:', error)
        throw error
      }
    },

    // 更新项目
    async updateProject(projectData) {
      try {
        const projectId = projectData.id || projectData._id
        
        // 只发送允许更新的字段
        const updateData = {
          name: projectData.name,
          description: projectData.description,
          protocolNumber: projectData.protocolNumber,
          version: projectData.version,
          status: projectData.status,
          config: projectData.config,
          configSections: projectData.configSections,
          isTemplate: projectData.isTemplate
        }
        
        // 移除 undefined 字段
        Object.keys(updateData).forEach(key => {
          if (updateData[key] === undefined) {
            delete updateData[key]
          }
        })
        
        const response = await api.projects.update(projectId, updateData)
        const updatedProject = response.data
        const index = this.projects.findIndex(p => (p.id || p._id) === projectId)
        if (index !== -1) {
          this.projects[index] = updatedProject
        }
        return updatedProject
      } catch (error) {
        console.error('更新项目失败:', error)
        throw error
      }
    },

    // 删除项目
    async deleteProject(projectId) {
      try {
        await api.projects.delete(projectId)
        const index = this.projects.findIndex(p => (p.id || p._id) === projectId)
        if (index !== -1) {
          this.projects.splice(index, 1)
        }
        return true
      } catch (error) {
        console.error('删除项目失败:', error)
        throw error
      }
    },

    // 设置当前项目
    setCurrentProject(project) {
      this.currentProject = project
    },

    // 生成 Word 文档
    async generateWord(projectData) {
      try {
        console.log('开始生成Word文档，项目数据:', projectData)
        
        // 获取完整的项目配置数据
        const projectConfig = await this.fetchProjectConfig(projectData._id || projectData.id);

        if (!projectConfig) {
          throw new Error('获取项目配置失败');
        }

        // 检查项目是否配置了章节
        if (!projectConfig.configSections || projectConfig.configSections.length === 0) {
          throw new Error('项目尚未配置章节，请先配置章节后再生成文档')
        }

        // 构造完整的文档数据
        const documentData = {
          ...projectConfig,
        };

        console.log('拼接完成的文档数据:', {
          name: documentData.name,
          sectionsCount: documentData.configSections.length,
          sections: documentData.configSections.map(s => ({
            name: s.name,
            formsCount: s.forms.length,
            forms: s.forms.map(f => ({ name: f.name, fieldsCount: f.config?.fields?.length || 0 }))
          }))
        })

        // 使用完整数据调用generateDocx
        await generateDocx(documentData)
      } catch (error) {
        console.error('生成 Word 文档失败:', error)
        throw error
      }
    },

    // 获取默认项目数据（fallback用）
    getDefaultProjectsData() {
      return [
        {
          id: 1,
          name: '示例项目1',
          version: '1.0.0',
          status: 'active',
          description: '这是一个示例项目',
          createTime: '2024-03-20 10:00:00',
          configSections: [
            {
              id: 1,
              name: '知情同意',
              forms: [
                {
                  id: 1,
                  name: '知情同意书',
                  config: {
                    fields: [
                      {
                        id: 1,
                        type: 'dateTimeGroup',
                        suffix: '获得知情同意',
                        value: {
                          year: 2024,
                          month: 3,
                          day: 20,
                          hour: 10,
                          minute: 30
                        }
                      },
                      {
                        id: 2,
                        type: 'radioWithInput',
                        value: {
                          label: '是否愿意参与本研究',
                          options: [
                            { value: 'yes', label: '愿意', showInput: false },
                            { value: 'no', label: '不愿意', showInput: true, inputLabel: '拒绝原因:' }
                          ],
                          selected: 'yes'
                        }
                      }
                    ]
                  }
                }
              ]
            },
            {
              id: 2,
              name: '入排标准',
              forms: [
                {
                  id: 2,
                  name: '入排标准评估',
                  config: {
                    fields: [
                      {
                        id: 3,
                        type: 'criteriaTable',
                        value: {
                          title: '入选标准',
                          columns: [
                            { id: 'seq', title: '序号', type: 'number', width: '80px' },
                            { id: 'criteria', title: '标准', type: 'text', width: 'auto' },
                            { id: 'result', title: '结果', type: 'radio', width: '120px', options: [
                              { value: 'yes', label: '符合' },
                              { value: 'no', label: '不符合' }
                            ]}
                          ],
                          rows: [
                            { seq: 1, criteria: '年龄≥18岁', result: 'yes' },
                            { seq: 2, criteria: '签署知情同意书', result: 'yes' }
                          ]
                        }
                      }
                    ]
                  }
                }
              ]
            }
          ]
        },
        {
          id: 2,
          name: '示例项目2',
          version: '1.0.0',
          status: 'completed',
          description: '这是另一个示例项目',
          createTime: '2024-03-19 14:30:00',
          configSections: []
        }
      ]
    }
  }
}) 